"""
将markdown转换成Latex 并生成PDF
"""

import os
import datetime
from pathlib import Path

from .utils import md2latex, sanitize_latex, run_pdflatex

class Convert2pdf:
    def __init__(self, temp_dir, title, keywords):
        self.temp_dir = temp_dir
        self.title = title
        self.keywords = keywords
        self.sections = ["Abstract", "Introduction", "Methods", "Results", "Discussion"]
        self.year = datetime.datetime.now().year

        self.paper=rf"""\documentclass[unnumsec,webpdf,contemporary,large]{{oup-authoring-template}}
\graphicspath{{{{Fig/}}}}
\theoremstyle{{thmstyleone}}
\newtheorem{{theorem}}{{Theorem}}
\newtheorem{{proposition}}[theorem]{{Proposition}}
\theoremstyle{{thmstyletwo}}
\newtheorem{{example}}{{Example}}
\newtheorem{{remark}}{{Remark}}
\theoremstyle{{thmstylethree}}
\newtheorem{{definition}}{{Definition}}

\begin{{document}}
\journaltitle{{Journal Title Here}}
\DOI{{DOI HERE}}
\copyrightyear{{{self.year}}}
\pubyear{{{self.year}}}
\access{{Advance Access Publication Date: Day Month Year}}
\appnotes{{Paper}}
\firstpage{{1}}
\title{{{sanitize_latex(self.title)}}}
\authormark{{Automatically generated by HAIant}}
\author{{Automatically generated by HAIant}}
\date{{{datetime.datetime.now().strftime("%B %d, %Y")}}}
\abstract{{$Abstract}}
\keywords{{{sanitize_latex(self.keywords)}}}
\maketitle
\section{{Introduction}}
$Introduction
\section{{Results}}
$Results
\section{{Discussion}}
$Discussion
\section{{Methods}}
$Methods

$Bibliography
\end{{document}}
        """
        self.__init()


    def file_reader(self, file_path):
        with open(file_path, "r", encoding="utf-8") as f:
            ctx = f.read()
            return ctx

    def __init(self):
        # 将markdown转换为latex
        md_files = [os.path.join(self.temp_dir, v) for v in os.listdir(self.temp_dir) if v.endswith(".md")]

        for md_file in md_files:
            if os.path.exists(md_file):
                md2latex(md_file)

        tex_files = [os.path.join(self.temp_dir, v) for v in os.listdir(self.temp_dir) if v.endswith(".tex") and v != "paper.tex"]
        for tex_file in tex_files:
            if os.path.exists(tex_file):
                path_obj = Path(tex_file)
                section = path_obj.stem
                print(section)
                ctx = self.file_reader(tex_file)
                self.paper = self.paper.replace(f"${section}", ctx)

        with open(f"{self.temp_dir}/paper.tex", "w", encoding="utf-8") as f:
            f.write(self.paper)

        # 将latex转换为pdf
        run_pdflatex(f"{self.temp_dir}/paper.tex")
